<template>
  <div class="app-container">
    <div class="filter-container">
      <el-input
        v-model="listQuery.title"
        placeholder="线路关键词"
        class="filter-item search-input"
        clearable
        @keyup.enter.native="handleFilter"
      />
      <el-select
        v-model="listQuery.startCity"
        placeholder="出发城市"
        clearable
        style="width: 120px"
        class="filter-item search-input"
      >
        <el-option v-for="item in startCityOptions" :key="item.value" :label="item.label.trim()" :value="item.value" />
      </el-select>
      <el-select
        v-model="listQuery.status"
        placeholder="线路状态"
        clearable
        style="width: 120px"
        class="filter-item search-input"
      >
        <el-option v-for="item in statusOptions" :key="item.value" :label="item.label" :value="item.value" />
      </el-select>
      <el-select
        v-model="listQuery.peerId"
        placeholder="分公司"
        clearable
        style="width: 190px"
        class="filter-item search-input"
      >
        <el-option v-for="item in peerOptions" :key="item.peerId" :label="item.name" :value="item.peerId" />
      </el-select>
      <el-button class="filter-item" type="primary" icon="el-icon-search" @click="handleFilter">
        搜索
      </el-button>
      <el-button class="filter-item" type="primary" icon="el-icon-download" @click="handleExport">
        导出
      </el-button>
      <el-button class="filter-item" type="primary" icon="el-icon-plus" @click="handleCreate">
        添加
      </el-button>
    </div>

    <!--  列表  -->
    <el-table
      :key="tableKey"
      v-loading="listLoading"
      :data="list"
      border
      fit
      highlight-current-row
      style="width: 100%;"
    >
      <el-table-column label="线路名" min-width="300px">
        <template slot-scope="{row}">
          <span>{{ row.title }}</span>
        </template>
      </el-table-column>
      <el-table-column label="出发城市" align="center">
        <template slot-scope="{row}">
          <span>{{ row.startCity }}</span>
        </template>
      </el-table-column>
      <el-table-column label="目的地" align="center">
        <template slot-scope="{row}">
          <span>{{ row.endCity }}</span>
        </template>
      </el-table-column>
      <el-table-column label="金额" align="center">
        <template slot-scope="{row}">
          <span style="font-weight :bold;">{{ row.price }}</span>
        </template>
      </el-table-column>
      <el-table-column label="线路状态" align="center">
        <template slot-scope="{row}">
          <el-tag :type="row.status == '已下架' ? 'danger' : (row.status == '草稿' ? 'info' : 'success') ">
            {{ row.status == '草稿' ? '&nbsp;草&nbsp;&nbsp;稿&nbsp;' : row.status }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column label="上线时间" min-width="150px" align="center">
        <template slot-scope="{row}">
          <span v-html="row.saleTime" />
        </template>
      </el-table-column>
      <el-table-column label="弱绑定" min-width="130px" align="center">
        <template slot-scope="{row}">
          <span v-html="row.peer" />
        </template>
      </el-table-column>
      <el-table-column label="操作" min-width="100px" align="center">
        <template slot-scope="{row}">
          <el-button size="small" type="primary" icon="el-icon-edit" @click="handleUpdate(row)">编辑</el-button>
          <!--        <el-button size="small" type="danger" plain>删除</el-button>-->
        </template>
      </el-table-column>
    </el-table>

    <!--  编辑页  -->
    <el-dialog :title="textMap[dialogStatus]" :visible.sync="dialogFormVisible" fullscreen>
      <el-form
        ref="dataForm"
        :rules="rules"
        :model="saveData"
        label-position="left"
        label-width="auto"
        style="width: 100%; margin-left:10px;"
      >
        <el-form-item label="名称" prop="title">
          <el-input v-model="saveData.title" placeholder="请输入名称" />
        </el-form-item>
        <el-form-item label="线路特色" prop="lineDesc">
          <el-input v-model="saveData.lineDesc" type="textarea" placeholder="请输入线路特色" />
        </el-form-item>
        <el-form-item label="出发城市" prop="startCity">
          <el-select v-model="saveData.startCity" class="filter-item" placeholder="请选择城市">
            <el-option
              v-for="item in startCityOptions"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="目的城市" prop="endCity">
          <el-select v-model="saveData.endCity" class="filter-item" placeholder="请选择目的城市">
            <el-option
              v-for="item in endCityOptions"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="销售价" prop="price">
          <el-input v-model="saveData.price" type="number" placeholder="请输入销售价" />
        </el-form-item>
        <!--        <el-form-item label="行程天数" prop="days">-->
        <!--          <el-input v-model="saveData.days" type="number" placeholder="请输入行程天数" />-->
        <!--        </el-form-item>-->
        <el-form-item label="返积分天数" prop="days">
          <el-input v-model="saveData.days" type="number" placeholder="请输入返积分天数" />
        </el-form-item>
        <el-form-item label="线路状态" prop="status">
          <el-select v-model="saveData.status" class="filter-item" placeholder="请选择线路状态">
            <el-option
              v-for="item in statusOptions"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="分公司弱绑定" prop="peerId">
          <el-select v-model="saveData.peerId" multiple class="filter-item" placeholder="请选择分公司">
            <el-option
              v-for="item in peerOptions"
              :key="item.peerId"
              :label="item.name"
              :value="item.peerId"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="线路行程" prop="lineInfo">
          <el-tabs type="border-card" @tab-click="tabClick">
            <el-tab-pane label="可视化编辑">
              <quill-editor
                ref="text"
                v-model="saveData.lineInfo"
                class="myQuillEditor"
                :options="{
                  placeholder:'请输入线路行程'
                }"
              />
            </el-tab-pane>
            <el-tab-pane label="按天编辑">
              <div v-for="(item, index) in addNextCount" :id="'id'+(index + 2)" :key="index" class="dayEdit">
                <el-form
                  label-position="left"
                  label-width="auto"
                  style="width: 100%; margin-left:10px;"
                >
                  <strong>第{{ item }}天行程</strong>
                  <el-divider />
                  <el-form-item label="标题">
                    <el-input v-model="lineInfoDay[index].title" placeholder="请输入标题" />
                  </el-form-item>
                  <el-form-item id="meal" label="用餐">
                    <div>
                      <div>
                        <el-checkbox v-model="lineInfoDay[index].breakfast" label="早餐" name="type" />
                        <el-input v-model="lineInfoDay[index].breakfastExplain" placeholder="早餐说明" />
                      </div>
                      <div>
                        <el-checkbox v-model="lineInfoDay[index].lunch" label="午餐" name="type" />
                        <el-input v-model="lineInfoDay[index].lunchExplain" placeholder="午餐说明" />
                      </div>
                      <div>
                        <el-checkbox v-model="lineInfoDay[index].dinner" label="晚餐" name="type" />
                        <el-input v-model="lineInfoDay[index].dinnerExplain" placeholder="晚餐说明" />
                      </div>
                    </div>
                  </el-form-item>
                  <el-form-item label="住宿">
                    <el-input v-model="lineInfoDay[index].getAccommodation" placeholder="请输入住宿" />
                  </el-form-item>
                  <el-form-item label="景点">
                    <el-input v-model="lineInfoDay[index].scenicSpots" placeholder="请输入景点" />
                  </el-form-item>
                  <el-form-item label="内容">
                    <el-input v-model="lineInfoDay[index].content" type="textarea" placeholder="请输入内容" />
                  </el-form-item>
                  <el-form-item label="图片">
                    <el-upload
                      v-model="lineInfoDay[index].pics"
                      :file-list="fileList"
                      :http-request="upload"
                      action="string1"
                      list-type="picture-card"
                      :limit="6"
                      :on-exceed="()=>{
                        this.$notify({
                          title: '上传失败',
                          message: '最多只能上传六张',
                          type: 'error',
                          duration: 2000
                        })}"
                    >
                      <i class="el-icon-plus" />
                    </el-upload>
                  </el-form-item>
                  <el-form-item>
                    <el-button type="primary" @click="addNext">添加下一天行程</el-button>
                  </el-form-item>
                </el-form>
              </div>
            </el-tab-pane>
          </el-tabs>
        </el-form-item>
        <el-form-item label="首图" prop="pic">
          <el-upload
            ref="upload"
            :http-request="upload"
            action="string"
            list-type="picture-card"
            :file-list="firstFileList"
            :before-remove="firstPicDeleteConfirm"
            :on-preview="handleFirstPicCardPreview"
            :limit="1"
            :on-exceed="()=>{
              this.$notify({
                title: '上传失败',
                message: '首图最多只能上传一张',
                type: 'error',
                duration: 2000
              })}"
          >
            <el-dialog :visible.sync="firstPicDialogVisible">
              <img width="100%" :src="firstDialogImageUrl" alt="">
            </el-dialog>
            <i class="el-icon-plus" />
          </el-upload>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">
          取消
        </el-button>
        <el-button type="primary" @click="dialogStatus==='create'?createData():updateData()">
          提交
        </el-button>
      </div>
    </el-dialog>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="listQuery.page"
      :limit.sync="listQuery.perPage"
      @pagination="getList"
    />
  </div>
</template>

<script>
import 'quill/dist/quill.core.css'
import 'quill/dist/quill.snow.css'
import 'quill/dist/quill.bubble.css'
import { get, list, update, upload as lineManagementUpload } from '@/api/lineManagement'
import { listStartCity, listSelection, listEndCity } from '@/api/selectOptions'
import { apiIp, toSelectOptions, confirm } from '@/utils/common'
import Pagination from '@/components/Pagination'
import { create } from '@/api/lineManagement'
import { checkMinVal } from '@/api/check'
import { quillEditor } from 'vue-quill-editor'

export default {
  components: {
    Pagination,
    quillEditor
  },
  data() {
    return {
      tableKey: 0,
      list: null,
      total: 0,
      listLoading: true,
      listQuery: {
        page: 1,
        perPage: 20,
        title: undefined,
        status: undefined,
        startCity: undefined,
        peerId: undefined,
        csv: undefined // 为1时，导出
      },
      startCityOptions: undefined,
      endCityOptions: undefined,
      peerOptions: undefined,
      statusOptions: [{ label: '草稿', value: '0' }, { label: '销售中', value: '1' }, { label: '已下架', value: '2' }],
      infoTypeOptions: [{ label: '可视化编辑', value: '0' }, { label: '按天编辑', value: '1' }],

      // 以下为编辑页属性
      firstFileList: [],
      fileList: [],
      firstPicDialogVisible: false,
      firstDialogImageUrl: '',
      picDialogVisible: false,
      dialogImageUrl: '',
      addNextCount: 1,
      dialogStatus: '',
      dialogFormVisible: false,
      lineInfoDay: [
        {
          title: '',
          breakfast: false,
          breakfastExplain: '',
          lunch: false,
          lunchExplain: '',
          dinner: false,
          dinnerExplain: '',
          getAccommodation: '',
          scenicSpots: '',
          content: '',
          pics: ''
        }
      ],
      saveData: {
        title: '',
        pic: '',
        status: '',
        price: '',
        startCity: '',
        endCity: '',
        peerId: '',
        days: '',
        lineDesc: '',
        lineInfo: '',
        infoType: ''
      },
      resetSaveData() {
        this.saveData = {
          title: '',
          pic: '',
          status: '',
          price: '',
          startCity: '',
          endCity: '',
          peerId: '',
          days: '',
          lineDesc: '',
          lineInfo: '',
          infoType: '0'
        }
        this.lineInfoDay = [
          {
            title: '',
            breakfast: false,
            breakfastExplain: '',
            lunch: false,
            lunchExplain: '',
            dinner: false,
            dinnerExplain: '',
            getAccommodation: '',
            scenicSpots: '',
            content: '',
            pics: ''
          }
        ]
      },
      textMap: {
        update: '编辑',
        create: '添加'
      },
      rules: {
        title: [{ required: true, message: '线路名不能为空', trigger: 'change' }],
        price: [
          { required: true, message: '销售价不能为空', trigger: 'change' },
          { validator: checkMinVal, trigger: 'blur' }
        ],
        startCity: [{ required: true, message: '出发城市不能为空', trigger: 'change' }],
        lineDesc: [{ required: true, message: '线路行程特色不能为空', trigger: 'change' }],
        endCity: [{ required: true, message: '目的城市不能为空', trigger: 'change' }],
        days: [{ required: true, message: '返积分天数不能为空', trigger: 'change' }],
        status: [{ required: true, message: '线路状态不能为空', trigger: 'change' }],
        peerId: [{ required: true, message: '分公司弱绑定不能为空', trigger: 'change' }],
        getAccommodation: [{ required: true, message: '住宿不能为空', trigger: 'change' }],
        scenicSpots: [{ required: true, message: '景点不能为空', trigger: 'change' }],
        content: [{ required: true, message: '内容不能为空', trigger: 'change' }],
        lineInfo: [{ required: true, message: '线路行程不能为空', trigger: 'change' }],
        pic: [{ required: true, message: '首图不能为空', trigger: 'change' }]
      }
    }
  },
  created() {
    this.getStartCityOptions()
    this.getEndCityOptions()
    this.getPeerOptions()
    this.getList()
  },
  methods: {
    tabClick(res) {
      this.saveData.infoType = res.paneName
    },
    getList() {
      this.listLoading = true
      list(this.listQuery).then(response => {
        this.list = response.data
        this.total = response.total
        this.listLoading = false
      })
    },
    upload(param) {
      this.listLoading = true
      const formData = new FormData()
      formData.append('file', param.file)
      lineManagementUpload(formData).then(response => {
        this.saveData.pic = response.data.imgName
        this.listLoading = false
      })
    },
    getStartCityOptions() {
      listStartCity().then(response => {
        this.startCityOptions = toSelectOptions(response.data)
      })
    },
    getEndCityOptions() {
      listEndCity().then(response => {
        this.endCityOptions = toSelectOptions(response.data)
      })
    },
    getPeerOptions() {
      listSelection().then(response => {
        this.peerOptions = response.data
      })
    },
    handleCreate() {
      this.resetSaveData()
      this.dialogStatus = 'create'
      this.dialogFormVisible = true
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
    },
    createData() {
      console.log(this.saveData.infoType)
      if (this.saveData.infoType === '') {
        this.saveData.infoType = '0'
      }
      if (this.saveData.infoType === '1') {
        this.saveData.lineInfo = this.lineInfoDay
      }

      if (this.saveData.peerId !== '') {
        this.saveData.peerId = this.saveData.peerId.join(',')
      }

      this.$refs['dataForm'].validate((valid) => {
        if (valid) {
          create(this.saveData).then(() => {
            this.list.unshift(this.saveData)
            this.dialogFormVisible = false
            this.$notify({
              title: '成功',
              message: '创建成功',
              type: 'success',
              duration: 2000
            })
            this.firstFileList =
              []
          })
        }
      })
    },
    handleUpdate(row) {
      this.dialogStatus = 'update'
      this.dialogFormVisible = true
      get({ ID: row.ID }).then(response => {
        this.saveData = Object.assign({}, response.data) // copy obj
        this.saveData.peerId = this.saveData.peerId.split(',')
        this.firstFileList.push({ url: apiIp + '/upload/line/' + response.data.pic })
        this.$nextTick(() => {
          this.$refs['dataForm'].clearValidate()
        })
      })
    },
    updateData() {
      if (this.saveData.infoType === '1') {
        this.saveData.lineInfo = this.lineInfoDay
      }
      this.$refs['dataForm'].validate((valid) => {
        if (valid) {
          this.saveData.peerId = this.saveData.peerId.join(',')
          update(this.saveData).then(() => {
            this.dialogFormVisible = false
            this.$notify({
              title: '成功',
              message: '更新成功',
              type: 'success',
              duration: 2000
            })
            this.firstFileList = []
            this.getList()
          })
        }
      })
    },
    handleDelete(row, index) {
      this.$notify({
        title: '成功',
        message: '删除成功',
        type: 'success',
        duration: 2000
      })
      this.list.splice(index, 1)
    },
    handleFilter() {
      this.listQuery.page = 1
      this.getList()
    },
    handleExport() {
      list(Object.assign(this.listQuery, { csv: 1 }), 'arraybuffer').then(response => {
        const content = response
        // 组装a标签
        const elink = document.createElement('a')
        // 设置下载文件名
        elink.download = '附件.csv'
        elink.style.display = 'none'
        const blob = new Blob([content], { type: '.csv, application/vnd.openxmlformats-officedocument.spreadsheetml.sheet, application/vnd.ms-excel' })
        elink.href = URL.createObjectURL(blob)
        document.body.appendChild(elink)
        elink.click()
        document.body.removeChild(elink)
        this.listQuery.csv = 0
      })
    },
    addNext() {
      this.addNextCount = this.addNextCount + 1
      this.lineInfoDay.push({
        ['title' + this.addNextCount]: '',
        ['breakfast' + this.addNextCount]: false,
        ['breakfastExplain' + this.addNextCount]: '',
        ['lunch' + this.addNextCount]: false,
        ['lunchExplain' + this.addNextCount]: '',
        ['dinner' + this.addNextCount]: false,
        ['dinnerExplain' + this.addNextCount]: '',
        ['getAccommodation' + this.addNextCount]: '',
        ['scenicSpots' + this.addNextCount]: '',
        ['content' + this.addNextCount]: '',
        ['pics' + this.addNextCount]: ''
      })
    },

    /**
     * 图片显示大图
     * @param file
     */
    handleFirstPicCardPreview(file) {
      this.firstDialogImageUrl = file.url
      this.firstPicDialogVisible = true
    },
    /**
     * 首图删除确认框
     * @returns {Promise<unknown>}
     */
    firstPicDeleteConfirm() {
      return confirm(this, '此操作将永久删除该文件, 是否继续?', () => {
        this.saveData.pic = ''
      })
    }
  }
}
</script>

<style>
.search-input {
  width: 150px;
  margin-right: 15px;
}

.dayEdit .el-input--medium {
  width: 90%;
}

.el-form-item {
  margin-bottom: 22px !important;
}

.el-divider--horizontal {
  margin-top: 10px;
}

#meal .el-form-item__label-wrap {
  height: 95px;
}

#meal .el-input {
  margin-left: 20px;
  width: 30%;
  margin-bottom: 5px;
}

.ql-editor {
  height: 200px;
}
</style>
